package com.sushi.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sushi.enums.Status;
import com.sushi.enums.Type;
import com.sushi.repository.entity.CommentEntity;
import com.sushi.repository.entity.PostEntity;
import com.sushi.repository.entity.TagEntity;
import com.sushi.repository.mapper.PostMapper;
import com.sushi.response.*;
import com.sushi.service.CommentService;
import com.sushi.service.FileService;
import com.sushi.service.PostService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sushi.request.PostReq;
import com.sushi.request.PostPageReq;
import com.sushi.service.TagService;
import com.sushi.utils.BeanUtil;
import com.sushi.utils.CollectionUtil;
import com.sushi.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import lombok.extern.slf4j.Slf4j;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sushi.exception.BusinessException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 交流帖 服务实现类
 * @date 2023-05-02
 * @time 17:15:45
 * @author Administrator
 */
@Slf4j
@Service
public class PostServiceImpl extends ServiceImpl<PostMapper, PostEntity> implements PostService {

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private TagService tagService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private FileService fileService;

    

    /**
     * 新增
     */
    @Override
    public ResponseBO<PostResp> add(PostReq req) {
        PostEntity entity = BeanUtil.convert(req, PostEntity.class);
        if (ObjectUtil.isEmpty(entity)) {
            throw new BusinessException("保存失败");
        }
        if (StringUtil.isNotBlank(req.getSaveType()) && StringUtil.equals(req.getSaveType(), "0")) {
            entity.setStatus(Status.Post.WAIT_COMMIT.getCode());
        }else {
            entity.setStatus(Status.Post.WAIT_CHECK.getCode());
        }
        if (CollectionUtil.isNotEmpty(req.getFileUrlList())) {
            String urls = StringUtil.join(req.getFileUrlList(), StringUtil.COMMA);
            entity.setFileUrls(urls);
        }
        entity.insert();
        if (CollectionUtil.isNotEmpty(req.getTagIdList())) {
            tagService.saveRelation(req.getTagIdList(), entity.getId(), Type.Tag.POST);
        }
        return ResponseUtil.ok(BeanUtil.convert(entity, PostResp.class));
    }

    /**
     * 逻辑删除
     */
    @Override
    public ResponseBO<PostResp> logicRemove(PostReq req) {
        log.info("删除id：{}", req.getId());
        if (StringUtil.isBlank(req.getId())) {
            throw new BusinessException("id不能为空");
        }
        PostEntity entity = getById(req.getId());
        removeById(req.getId());
        return ResponseUtil.ok(BeanUtil.convert(entity, PostResp.class));
    }

    /**
     * 更新
     */
    @Override
    public ResponseBO<PostResp> updateByField(PostReq req) {
        if (ObjectUtil.isEmpty(req) || StringUtil.isBlank(req.getId())) {
            throw new BusinessException("必要参数不能为空");
        }
        PostEntity entity = getById(req.getId());
        if (ObjectUtil.isEmpty(entity)) {
            return ResponseUtil.error("信息不存在，无法更新");
        }
        if (StringUtil.isNotBlank(req.getTitle())) {
            entity.setTitle(req.getTitle());
        }
        if (StringUtil.isNotBlank(req.getType())) {
            entity.setType(req.getType());
        }
        if (StringUtil.isNotBlank(req.getContent())) {
            entity.setContent(req.getContent());
        }
//        if (StringUtil.isNotBlank(req.getTagIds())) {
//            entity.setTagIds(req.getTagIds());
//        }
//        if (StringUtil.isNotBlank(req.getFileUrls())) {
//            entity.setFileUrls(req.getFileUrls());
//        }
        if (StringUtil.isNotBlank(req.getStatus())) {
            entity.setStatus(req.getStatus());
        }
        if (StringUtil.isNotBlank(req.getBackReason())) {
            entity.setBackReason(req.getBackReason());
        }

        entity.updateById();
        log.info("更新成功：{}", JSON.toJSONString(entity));
        return ResponseUtil.ok(BeanUtil.convert(entity, PostResp.class));
    }

    /**
     * 列表
     */
    @Override
    public ResponsePageBO<PostResp> listByCondition(PostPageReq req) {
        log.info("入参：{}", JSON.toJSONString(req));
        if (ObjectUtil.isEmpty(req) || ObjectUtil.isEmpty(req.getPageNum()) || ObjectUtil.isEmpty(req.getPageSize())) {
            throw new BusinessException("必要参数不能为空");
        }
        LambdaQueryWrapper<PostEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PostEntity::getDeleted, 0L);
        wrapper.eq(StringUtil.isNotBlank(req.getId()), PostEntity::getId, req.getId());
        wrapper.eq(StringUtil.isNotBlank(req.getStatus()), PostEntity::getStatus, req.getStatus());
        wrapper.like(StringUtil.isNotBlank(req.getTitle()), PostEntity::getTitle, req.getTitle());
        wrapper.eq(StringUtil.isNotBlank(req.getType()), PostEntity::getType, req.getType());
        wrapper.like(StringUtil.isNotBlank(req.getContent()), PostEntity::getContent, req.getContent());

        String searchContent = req.getSearchContent();
        if (StringUtil.isNotBlank(searchContent)) {
            wrapper.and(w -> w.or().like(PostEntity::getContent, searchContent).or().like(PostEntity::getTitle, searchContent).
                    or().like(PostEntity::getCreatorName, searchContent));
        }

        if (CollectionUtil.isNotEmpty(req.getTagIdList())) {
            List<String> relationList = tagService.getRalationIdList(req.getTagIdList(), Type.Tag.POST);
            if (CollectionUtil.isEmpty(relationList)) {
                return ResponsePageUtil.ok(req, new ArrayList<>(), 0L);
            }
            wrapper.in(PostEntity::getId, relationList);
        }
//        wrapper.eq(StringUtil.isNotBlank(req.getStatus()), PostEntity::getStatus, req.getStatus());
        wrapper.like(StringUtil.isNotBlank(req.getBackReason()), PostEntity::getBackReason, req.getBackReason());

        wrapper.orderByDesc(PostEntity::getGmtCreateTime);

        Page<PostEntity> page = page(new Page<>(req.getPageNum(), req.getPageSize()), wrapper);
        if (ObjectUtil.isEmpty(page) || CollectionUtil.isEmpty(page.getRecords())) {
            return ResponsePageUtil.ok(req, new ArrayList<>(), 0L);
        }
        List<PostResp> convert = BeanUtil.convert(page.getRecords(), PostResp.class);
        fillTagInfo(convert);
        return ResponsePageUtil.ok(req, convert, page.getTotal());

    }

    private void fillTagInfo(List<PostResp> convert) {
        if (CollectionUtil.isNotEmpty(convert)) {
            convert.forEach(resp -> {
                List<TagResp> tagList = tagService.getTagListByObjId(resp.getId(), Type.Tag.POST);
                resp.setTagList(tagList);
            });
        }
    }

    /**
     * 详情
     */
    @Override
    public ResponseBO<PostResp> detail(PostReq req) {
        log.info("入参：{}", JSON.toJSONString(req));
        if (ObjectUtil.isEmpty(req) || StringUtil.isBlank(req.getId())) {
            throw new BusinessException("必要参数不能为空");
        }
        PostEntity entity = getById(req.getId());
        PostResp convert = BeanUtil.convert(entity, PostResp.class);
        if (ObjectUtil.isEmpty(convert)) {
            throw new BusinessException("对象不存在");
        }
        convert.setTagList(tagService.getTagListByObjId(convert.getId(), Type.Tag.POST));
        // 评论封装
        List<CommentResp> commentRespList = commentService.getPostComments(convert.getId());
        convert.setCommentList(commentRespList);
//        convert.setCommentList(new ArrayList<>());

        //文件
        String[] files = entity.getFileUrls().split(StringUtil.COMMA);
        List<FileResp> fileList = fileService.listByIdList(Arrays.asList(files));
        convert.setFileList(fileList == null ? new ArrayList<>() : fileList);
//        convert.setFileList(new ArrayList<>());

        return ResponseUtil.ok(convert);
    }


}